<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userNumber">
        <el-input
          v-model="queryParams.userNumber"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所在地区" prop="addressId">
        <el-cascader v-model="queryParams.addressId" :options="options" :props="typeS"  clearable/>
      </el-form-item>
      <el-form-item label="接入车系" prop="vehicleId">
        <el-cascader v-model="queryParams.vehicleId" :options="options2" :props="typeS2"  clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['userInfo:userInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['userInfo:userInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['userInfo:userInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['userInfo:userInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="用户ID" align="center" prop="userNumber" />
      <el-table-column label="用户姓名" align="center" prop="name" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="所在地区" align="center" prop="addressId" >
        <template v-slot="s">
          <!--将三级联动信息回显到表格中，只显示文字-->
          {{ formatAddress(s.row.addressId) }}
        </template>
      </el-table-column>
      <el-table-column label="接入车系" align="center" prop="vehicleId" >
        <template v-slot="s">
          <!--将三级联动信息回显到表格中，只显示文字-->
          {{ formatVehicle(s.row.vehicleId) }}
        </template>
      </el-table-column>
      <el-table-column label="绑定设备数量" align="center" prop="bindsNumber"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['userInfo:userInfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['userInfo:userInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户数据对话框 -->
    <el-drawer
        v-model="open"
        :title="title"
        direction="rtl"
        size="60%"
    >
      <el-form ref="userInfoRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userNumber">
          <el-input v-model="form.userNumber" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="所在地区" prop="addressId">
          <el-cascader v-model="form.addressId" :options="options" :props="typeS" style="width: 400px" clearable/>
        </el-form-item>
        <el-form-item label="接入车系" prop="vehicleId">
          <el-cascader v-model="form.vehicleId" :options="options2" :props="typeS2"  clearable/>
        </el-form-item>
        <el-divider content-position="center">用户绑定产品信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddIacProduct">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteIacProduct">删除</el-button>
          </el-col>
        </el-row>


        <el-table :data="iacProductList" :row-class-name="rowIacProductIndex" @selection-change="handleIacProductSelectionChange" ref="iacProduct">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="绑定产品名称" prop="productName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.productName" placeholder="请输入绑定产品名称" />
            </template>
          </el-table-column>
          <el-table-column label="绑定设备名称" prop="equipmentName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.equipmentName" placeholder="请输入绑定设备名称" />
            </template>
          </el-table-column>
          <el-table-column label="绑定状态" prop="status" width="150">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.productStatus"
                  class="ml-2"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="绑定时长" prop="bindDuration" width="150">
            <template #default="scope">
              {{scope.row.bindDuration}}
            </template>
          </el-table-column>
          <el-table-column label="绑定时间" prop="bindTime" width="240">
            <template #default="scope">
<!--              <el-date-picker-->
<!--                  v-model="scope.row.bindTime"-->
<!--                  type="datetime"-->
<!--                  value-format="YYYY-MM-DD HH:mm:ss"-->
<!--                  placeholder="请选择绑定时间"-->
<!--                  @change="updateBindDuration(scope.row)"-->
<!--              />-->
              {{scope.row.bindTime}}
            </template>
          </el-table-column>
          <el-table-column label="解绑时间" prop="untyingTime" width="240">
            <template #default="scope">
<!--              <el-date-picker clearable-->
<!--                v-model="scope.row.untyingTime"-->
<!--                type="datetime"-->
<!--                placeholder="请选择解绑时间"-->
<!--                value-format="YYYY-MM-DD HH:mm:ss"-->
<!--                @change="updateBindDuration(scope.row)"-->
<!--              >-->
<!--              </el-date-picker>-->
              {{scope.row.untyingTime}}
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="UserInfo">
import {
  listUserInfo,
  getUserInfo,
  delUserInfo,
  addUserInfo,
  updateUserInfo,
  typeData,
  carSeriesData, getProductNumber
} from "@/api/userInfo/userInfo";
import { onBeforeUnmount } from 'vue';

const { proxy } = getCurrentInstance();

const userInfoList = ref([]);
const iacProductList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedIacProduct = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const options = ref([])
const options2 = ref([])
const bindNumber = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userNumber: null,
    name: null,
    addressId: null,
    vehicleId: null,
  },
  rules: {
    userNumber: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "用户姓名不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "联系方式不能为空", trigger: "blur" }
    ],
    age: [
      { required: true, message: "年龄不能为空", trigger: "blur" }
    ],
    addressId: [
      { required: true, message: "所在地区不能为空", trigger: "blur" }
    ],
    vehicleId: [
      { required: true, message: "接入车系不能为空", trigger: "blur" }
    ],
    productId: [
      { required: true, message: "绑定产品不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


/** 查询用户数据列表 */
function getList() {
  loading.value = true;
  listUserInfo(queryParams.value).then(response => {
    userInfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userNumber: null,
    name: null,
    phone: null,
    age: null,
    addressId: null,
    vehicleId: null,
    productId: null,
    createTime: null
  };
  iacProductList.value = [];
  proxy.resetForm("userInfoRef");
}

const typeS = ref({
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: true,
  emitPath: false
})

const typeS2 = ref({
  value: 'id',
  label: 'carName',
  children: 'children',
  checkStrictly: true,
  emitPath: false
})


const typeBoyTwo = ()=>{
  typeData().then(res=>{
    if (res.code==200){
      options.value=res.data;
    }
  })
}

const carSeriesDto = () =>{
  carSeriesData().then(res=>{
    if (res.code==200){
      options2.value = res.data;
    }
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户数据";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getUserInfo(_id).then(response => {
    form.value = response.data;
    iacProductList.value = response.data.iacProductList;
    response.data.iacProductList.forEach(item=>{
      if (item.status==1){
        //将productStatus赋值成ture
        item.productStatus=true;
      }
    })
    open.value = true;
    title.value = "修改用户数据";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userInfoRef"].validate(valid => {
    if (valid) {
      form.value.iacProductList = iacProductList.value;
      if (form.value.id != null) {
        updateUserInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUserInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除用户数据编号为"' + _ids + '"的数据项？').then(function() {
    return delUserInfo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 用户绑定产品序号 */
function rowIacProductIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 用户绑定产品添加按钮操作 */
function handleAddIacProduct() {
  let obj = {};
  obj.productName = "";
  obj.equipmentName = "";
  obj.status = "";
  obj.bindDuration = null;
  obj.bindTime = "";
  obj.untyingTime = "";
  obj.productStatus = true;   //默认启动
  iacProductList.value.push(obj);
}

/** 用户绑定产品删除按钮操作 */
function handleDeleteIacProduct() {
  if (checkedIacProduct.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的用户绑定产品数据");
  } else {
    const iacProducts = iacProductList.value;
    const checkedIacProducts = checkedIacProduct.value;
    iacProductList.value = iacProducts.filter(function(item) {
      return checkedIacProducts.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleIacProductSelectionChange(selection) {
  checkedIacProduct.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('userInfo/userInfo/export', {
    ...queryParams.value
  }, `userInfo_${new Date().getTime()}.xlsx`)
}

// 添加 formatAddress 方法
function formatAddress(addressId) {
  // 假设 options 是你的地区数据
  const findAddress = (options, id) => {
    for (const option of options) {
      if (option.id === id) return option.name;
      if (option.children) {
        const result = findAddress(option.children, id);
        if (result) return `${option.name} / ${result}`;
      }
    }
    return '';
  };

  return findAddress(options.value, addressId);
}

function formatVehicle(vehicleId) {
  const findVehicle = (options, id) => {
    for (const option of options) {
      if (option.id === id) return option.carName;
      if (option.children) {
        const result = findVehicle(option.children, id);
        if (result) return `${option.carName} / ${result}`;
      }
    }
    return '';
  };

  return findVehicle(options2.value, vehicleId);
}

async function updateBindDuration() {
  // 1. 参数校验
  if (!this.duration || this.duration <= 0) {
    ElMessage.error('请输入有效的绑定时长')
    return
  }

  try {
    this.loading = true // 2. 加载状态控制
    // 3. 调用后端接口
    const { code } = await updateUserBindDuration({
      userId: this.currentUser.id,
      duration: this.duration
    })

    // 4. 处理响应
    if (code === 200) {
      ElMessage.success('绑定时长更新成功')
      this.fetchUserInfo() // 5. 重新获取最新数据
    }
  } catch (error) {
    ElMessage.error('更新失败：' + (error.message || '服务器异常'))
  } finally {
    this.loading = false
  }
}


const bindingTime = ref('2024-05-20 10:00:00') // 你的绑定时间
const duration = ref('')

const calculateDuration = () => {
  const now = new Date()
  const target = new Date(bindingTime.value)
  const diff = now - target // 时间差（毫秒）

  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((diff % (1000 * 60)) / 1000)

  duration.value = `${days}天${hours}小时${minutes}分${seconds}秒`
}

let timer = null

onMounted(() => {
  typeBoyTwo();
  carSeriesDto();
 calculateDuration()
 timer = setInterval(calculateDuration, 1000)
})

onBeforeUnmount(() => {
  clearInterval(timer)
})

getList();
</script>
